
import './DevExtremeConfig.scss'
import { v4 } from 'uuid'
import dayjs from 'dayjs'
import { jsPDF } from 'jspdf'
import { Workbook } from 'exceljs'
import { saveAs } from 'file-saver'
import { useRequest } from 'alova/client'
import { useEventEmitter, useMount } from 'ahooks'
import CustomStore from 'devextreme/data/custom_store'
import { memo, useEffect, useState, useRef, useCallback } from 'react'
import { App, Button, Skeleton, Dropdown, Result, Tree, Tooltip, FloatButton } from "antd"
import { SearchOutlined, RedoOutlined, VerticalAlignTopOutlined, VerticalAlignBottomOutlined } from '@ant-design/icons'


import {
    DataGrid,
    Column,
    Lookup,
    Scrolling,
    FilterRow,
    HeaderFilter,
    SearchPanel,
    GroupPanel,
    Grouping,
    ColumnFixing,
    Summary,
    GroupItem,
    TotalItem,
    Sorting,
    Selection,
    RowDragging,
    Export,
    LoadPanel,
    ColumnChooser,
    ColumnChooserSearch,
    ColumnChooserSelection,
    Position,
    Paging,
    Search
} from 'devextreme-react/data-grid'

import TreeList from 'devextreme-react/tree-list'
import Pagination from 'devextreme-react/pagination'
import Splitter, { Item } from 'devextreme-react/splitter'
import { exportPivotGrid } from 'devextreme/excel_exporter'
import PivotGridDataSource from 'devextreme/ui/pivot_grid/data_source'
import { exportDataGrid as exportExcel } from 'devextreme/excel_exporter'
import { exportDataGrid as exportPDF } from 'devextreme-react/common/export/pdf'
import { PivotGrid, FieldChooser, FieldPanel, StateStoring } from 'devextreme-react/pivot-grid'

import { Http } from '../Utils/Api'
import { GetIndexedDB } from './IndexedDB'
import { AdminRouter } from '../Config/default'
import { ICONMapping } from '../Config/IconMapping'
import { MappingData } from '../Config/MappingData'
import { ColorCallBack, filterTreeData, strOfurlParamsFunc } from '../Utils'
import { modelStore, drawerStore, devChartsStore, pageStore } from '../Config/zustand'


const { port } = window.location


const CellRender = ({ data, field, temp }) => {
    switch (temp) {
        case 'icon': return data.value ? ICONMapping[data.value] : '-'
        case 'date': return data.value ? dayjs(data.value).format(field.dateRender) : '-'
        default: return '未知模板,请联系管理员'
    }
}

const LookupTemplate = ({ data }) => {
    const { send } = useRequest(data => Http(data), { immediate: false })
    const { mappingType, mappingLable, mappingValue, mappingData, mappingApi, mappingPar } = data

    const [dataSource, setDataSource] = useState([])

    const lookupDataSource = {
        store: new CustomStore({
            key: "value",
            load: async () => {
                if (mappingType === 'DataMapping') {
                    return MappingData[mappingData]
                }
                if (mappingType === 'ApiMapping') {
                    const data = await send({ method: 'get', url: mappingApi, params: { ...strOfurlParamsFunc(mappingPar) } })
                    return data.data.list
                }
            }
        })
    }

    return (
        <Lookup
            dataSource={lookupDataSource}
            valueExpr={mappingValue}
            displayExpr={mappingLable}
        />
    )
}

// 显示字段
const DevFieldTemplate = memo(({ fieldArr, fieldRender }) => {
    return fieldRender?.filter(v => v.visible).map(item => {
        const { id, children } = item
        if (children) {
            return (
                <Column
                    key={id}
                    caption={item.caption}
                    alignment={item.alignment}
                    fixed={item.fixed}
                    fixedPosition={item.fixedPosition}
                >
                    <DevFieldTemplate fieldArr={fieldArr} fieldRender={item.children} />
                </Column>
            )
        } else {
            const fieldData = fieldArr.find(v => v.id === item.id)
            const { id, dataField, caption, visible, isAdded, isMapping, isModify, valueType, rules, // 无用属性
                dataType, customizeText, cssClass, calculateCellValue,  //删除属性
                format, formatType, formatPrecision, // 数值格式化属性
                groupIndex, defaultSortIndex, defaultSortOrder, // 分组排序参数
                mappingType, mappingLable, mappingValue, mappingData, mappingApi, mappingPar,   // 映射关系
                cellRender, cellRenderTemp,// 额外渲染
                ...pop // dev系统参数
            } = fieldData
            return (
                <Column
                    key={item.id}
                    dataField={item.dataField ? item.dataField : item.caption}
                    caption={item.caption}
                    format={format ? { type: formatType, precision: formatPrecision } : format}
                    {...pop}
                    cellRender={cellRender ? e => <CellRender data={e} temp={cellRenderTemp} field={fieldData} /> : false}
                >
                    {mappingType !== 'none' && <LookupTemplate data={fieldArr.find(v => v.id === item.id)} />}
                </Column>
            )
        }
    })
})

// 行内操作
const DevRowOptionTemplate = ({ data }) => {
    if (!data) return false

    const {
        itemMargin, itemOrder, iconSize, iconShadowX, iconShadowY, iconShadowS, iconShadowB,
        fontFamily, fontWeight, fontStyle, fontSize, fontShadowX, fontShadowY, fontShadowS, fontShadowB, ...columnData
    } = data


    const BtnStyle = {
        '--itemMargin': itemMargin + 'px',
        '--iconSize': iconSize,
        '--iconFilter': `drop-shadow(${iconShadowX}px ${iconShadowY}px ${iconShadowS}px ${iconShadowB})`,
        '--fontFamily': fontFamily,
        '--fontWeight': fontWeight,
        '--fontStyle': fontStyle,
        '--fontSize': fontSize,
        '--fontFilter': `drop-shadow(${fontShadowX}px ${fontShadowY}px ${fontShadowS}px ${fontShadowB})`,
    }

    return (
        <Column
            {...columnData}
            cellRender={e => {
                return (
                    <div className='RowOptions' style={BtnStyle}>
                        <Tooltip title='操作'>
                            <Button
                                type='link'
                                icon={itemOrder.includes('icon') && ICONMapping['weixingongzhonghao']}
                            >
                                {itemOrder.includes('text') && '操作'}
                            </Button>
                        </Tooltip>
                    </div>
                )
            }}
        />
    )
}

const onExporting = (e) => {
    const { format, component } = e
    if (format === 'xlsx') {
        const workbook = new Workbook()
        const worksheet = workbook.addWorksheet('Main sheet')
        exportExcel({ component: component, worksheet, autoFilterEnabled: true }).then(() =>
            workbook.xlsx.writeBuffer().then((buffer) => saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'DataGrid.xlsx'))
        )
    }
    if (format === 'pdf') {
        const doc = new jsPDF();
        exportPDF({ jsPDFDocument: doc, component: component, indent: 5, }).then(() => { doc.save('Companies.pdf') })
    }
}

const sortFunction = (arr) => {
    return arr.filter(item => item.sort !== 'none').reduce((acc, item, index) => {
        acc[item.value] = `${item.sort}@${index}`
        return acc
    }, {})
}

// 统计组件
const SummaryTemplate = ({ fieldArr }) => {
    const totalArr = fieldArr.filter(v => v.totalItemStatus)
    const groupArr = fieldArr.filter(v => v.groupItemStatus)
    return (
        <div>
            <Summary>
                {totalArr?.length !== 0 && totalArr.map((item, index) => (
                    <TotalItem
                        key={index}
                        column={item.dataField}
                        summaryType={item.totalSummaryType}
                        showInColumn={item.totalShowInColumn}
                        alignment={item.totalAlignment}
                        valueFormat={item.format ? { type: item.formatType, precision: item.formatPrecision } : false}
                        displayFormat={`${item.totalDisplayFormat || ''}{0}`}
                    />
                ))}

                {groupArr.length !== 0 && groupArr.map((item, index) =>
                    <GroupItem
                        key={index}
                        column={item.dataField}
                        summaryType={item.groupSummaryType}
                        valueFormat={item.format ? { type: item.formatType, precision: item.formatPrecision } : false}
                        displayFormat={`${item.groupDisplayFormat || ''}{0}`}
                    />
                )}
            </Summary>
        </div>
    )
}

// 数据表格
const DevExtremeDataGrid = ({ menuUuid, config, APIdata, fieldRender, DateEvent, rowStyle, treeList }) => {
    const ref = useRef()
    const {
        method, apiUrl, params, pageOptions, pageSize, fieldArr, isMenuUuid, uuidParams,
        PaginationMode, PaginationShowInfo, PaginationShowNavigationButtons, PaginationShowPageSizeSelector
    } = APIdata

    const [PageIndex, setPageIndex] = useState(1)
    const [PageSize, setPageSize] = useState(pageSize)
    const [ORGUUID, setORGUUID] = useState()
    const [TREEUUID, setTREEUUID] = useState()

    const [Data, setData] = useState()
    const [Total, setTotal] = useState()

    const [SortData, setSortData] = useState({})
    const [SearchData, setSearchData] = useState({})
    const [focusedRowKey, setFocusedRowKey] = useState()

    const [SelectedRowKeys, setSelectedRowKeys] = useState([])

    const { send } = useRequest(data => Http(data), { immediate: false })

    const onOptionChanged = e => {
        const { name, fullName, value } = e
        if (name === 'paging') {
            if (fullName === 'paging.pageIndex') setPageIndex(value)
            if (fullName === 'paging.pageSize') setPageSize(value)
        }
    }

    const getData = () => {
        const paramsData = {
            ...strOfurlParamsFunc(params),
            menuUuid,
            organizationUuid: ORGUUID,
            PageIndex,
            PageSize,
            ...SearchData,
            ...SortData,
        }
        if (treeList) paramsData[treeList.addParams] = TREEUUID
        if (isMenuUuid) paramsData[uuidParams] = menuUuid
        send({ method: method, url: apiUrl, params: paramsData }).then(res => {
            setTotal(res.data.total)
            setData(res.data.list)
        })
    }

    useEffect(() => {
        if (ORGUUID) {
            if (treeList && TREEUUID) {
                getData()
            } else getData()
        }
    }, [ORGUUID, PageSize, ORGUUID, PageIndex, SearchData, SortData, TREEUUID])


    const CallBackFunc = (e) => {
        const { type, data } = e
        const MapReturn = new Map([
            ['onSelectOrg', () => setORGUUID(data)],
            ['onLeftTree', () => setTREEUUID(data)],
            ['onSearchData', () => setSearchData(data)],
            ['onSortData', () => setSortData(sortFunction(data))],
            ['onRefresh', () => {
                setFocusedRowKey(null)
                if (data) {
                    const { search, sort } = data
                    !sort && setSortData([])
                    !search && setSearchData([])
                    if (search && sort) getData()
                } else getData()
            }]
        ])
        const func = MapReturn.get(type)
        return func && func()
    }

    DateEvent.useSubscription(CallBackFunc)

    const onFocusedRowChanged = data => {
        DateEvent.emit({ type: 'onFocusedRow', data })
        setFocusedRowKey(data.component.option('focusedRowKey'))
    }

    const onSelectionChanged = (e) => {
        DateEvent.emit({ type: 'onSelected', data: e.selectedRowKeys })
    }

    if (config) {
        if (ORGUUID) {
            return (
                <>
                    <DataGrid
                        ref={ref}
                        id={v4()}
                        width='100%'
                        keyExpr='uuid'
                        // 基础数据
                        dataSource={Data}
                        focusedRowKey={focusedRowKey}
                        focusedRowEnabled={config.focusedRowEnabled}
                        // 边框线
                        showBorders={config.showBorders}
                        showRowLines={config.showRowLines}
                        showColumnLines={config.showColumnLines}
                        rowAlternationEnabled={config.rowAlternationEnabled}
                        // 列设置
                        allowColumnResizing={config.allowColumnResizing}
                        columnResizingMode={config.columnResizingMode}
                        showColumnHeaders={config.showColumnHeaders}

                        defaultSelectedRowKeys={SelectedRowKeys}
                        onSelectionChanged={onSelectionChanged}
                        onFocusedRowChanged={onFocusedRowChanged}

                        onOptionChanged={onOptionChanged}
                        onExporting={onExporting}
                    >
                        {/* 显示字段 */}
                        <DevFieldTemplate fieldArr={fieldArr} fieldRender={fieldRender} />
                        <DevRowOptionTemplate data={rowStyle} />

                        {/* 固定列 */}
                        <ColumnFixing enabled={config.columnFixingEnabled} />
                        {/* 列选择器 */}
                        <ColumnChooser
                            enabled={config.columnChooserEnabled}
                            title={config.columnChooserTitle}
                            mode={config.columnChooserMode}
                            width={config.columnChooserWidth}
                            height={config.columnChooserHeight}
                        >
                            <Position my="right top" at="right bottom" of=".dx-datagrid-column-chooser-button" />
                            <ColumnChooserSearch
                                enabled={config.columnChooserSearch}
                                timeout={config.columnChooserTimeout}
                                editorOptions={{ placeholder: config.columnChooserPlaceholder }}
                            />
                            <ColumnChooserSelection
                                allowSelectAll={config.ColumnChooserAllowSelectAll}
                                selectByClick={config.ColumnChooserSelectByClick}
                                recursive={config.ColumnChooserRecursive}
                            />
                        </ColumnChooser>
                        {/* 分组面板 */}
                        <GroupPanel
                            visible={config.GroupPanelVisible}
                            autoExpandAll={config.GroupPanelAutoExpandAll}
                            allowColumnDragging={config.GroupPanelAllowColumnDragging}
                            emptyPanelText={config.GroupPanelEmptyPanelText}
                        />
                        <Grouping
                            allowCollapsing={config.GroupingAllowCollapsing}
                            autoExpandAll={config.GroupingAutoExpandAll}
                            contextMenuEnabled={config.GroupingContextMenuEnabled}
                            expandMode={config.GroupingExpandMode}
                        />
                        {/* 排序 */}
                        <Sorting
                            mode={config.Sortingmode}
                            showSortIndexes={config.SortingshowSortIndexes}
                            ascendingText={config.SortingascendingText}
                            descendingText={config.SortingdescendingText}
                            clearText={config.SortingclearText}
                        />
                        {/* 选择 */}
                        <Selection
                            mode={config.SelectionMode}
                            allowSelectAll={config.SelectionAllowSelectAll}
                            selectAllMode={config.SelectionSelectAllMode}
                            showCheckBoxesMode={config.SelectionShowCheckBoxesMode}
                        />
                        {/* 导出 */}
                        <Export
                            enabled={config.ExportEnabled}
                            allowExportSelectedData={config.ExportAllowExportSelectedData}
                            formats={config.ExportFormats}
                        />
                        {/* 过滤器 */}
                        <HeaderFilter
                            visible={config.HeaderFilterVisible}
                            allowSelectAll={config.HeaderFilterAllowSelectAll}
                            width={config.HeaderFilterWidth}
                            height={config.HeaderFilterHeight}
                        >
                            <Search enabled={config.HeaderFilterEnabled} />
                        </HeaderFilter>
                        {/* 头部搜索 */}
                        <SearchPanel
                            visible={config.SearchPanelVisible}
                            highlightCaseSensitive={config.SearchPanelHighlightCaseSensitive}
                            highlightSearchText={config.SearchPanelHighlightSearchText}
                            placeholder={config.SearchPanelPlaceholder}
                            searchVisibleColumnsOnly={config.SearchPanelSearchVisibleColumnsOnly}
                            defaultText={config.SearchPanelText}
                            width={config.SearchPanelWidth}
                        />
                        {/* 行内搜索 */}
                        <FilterRow
                            visible={config.FilterRowVisible}
                            applyFilter={config.FilterRowApplyFilter}
                            applyFilterText={config.FilterRowApplyFilterText}
                        />
                        <SummaryTemplate fieldArr={fieldArr} />
                        <Scrolling
                            rowRenderingMode="virtual"
                            columnRenderingMode="virtual"
                            mode="virtual"
                            scrollByContent={true}
                            showScrollbar='onHover'
                        />
                        <Paging defaultPageSize={9999999} />
                    </DataGrid>
                    {/* 分页 */}
                    {pageOptions !== '0' &&
                        <Pagination
                            showInfo={PaginationShowInfo}
                            showPageSizeSelector={PaginationShowPageSizeSelector}
                            showNavigationButtons={PaginationShowNavigationButtons}
                            itemCount={Total}
                            pageIndex={PageIndex}
                            pageSize={PageSize}
                            infoText='第{0}页，共{1}页 ({2} 项)'
                            onPageIndexChange={setPageIndex}
                            onPageSizeChange={setPageSize}
                            allowedPageSizes={pageOptions.split(',').map(item => Number(item))}
                            displayMode={PaginationMode}
                        />
                    }
                </>
            )
        } else {
            return <Skeleton active paragraph={{ rows: 24 }} />
        }
    } else {
        return (
            <Result
                status="404"
                title="未检测到模板信息"
                subTitle="抱歉,未检测到模板配置信息,请检查网络或联系管理员!"
            />
        )
    }
}
// 树形表格
const DevExtremeTreeGrid = ({ menuUuid, config, APIdata, fieldRender, DateEvent, rowStyle }) => {
    const { method, apiUrl, fieldArr, params, isMenuUuid, uuidParams } = APIdata

    const [Data, setData] = useState()
    const [ORGUUID, setORGUUID] = useState()
    const [SearchData, setSearchData] = useState({})
    const [SortData, setSortData] = useState({})
    const [focusedRowKey, setFocusedRowKey] = useState()
    const [SelectedRowKeys, setSelectedRowKeys] = useState([])

    const { send } = useRequest(data => Http(data), { immediate: false })

    const getData = () => {
        const paramsData = {
            ...strOfurlParamsFunc(params),
            menuUuid,
            organizationUuid: ORGUUID,
            ...SearchData,
            ...SortData
        }
        if (isMenuUuid) paramsData[uuidParams] = menuUuid
        send({ method: method, url: apiUrl, params: paramsData }).then(res => {
            setData(res.data.list)
        })
    }

    useEffect(() => {
        if (ORGUUID) { getData() }
    }, [ORGUUID, SearchData, SortData])

    const onDestroy = () => {
        // console.log('销毁Dev', DateEvent)
    }

    const CallBackFunc = (e) => {
        const { type, data } = e
        const MapReturn = new Map([
            ['onSelectOrg', () => setORGUUID(data)],
            ['onSearchData', () => setSearchData(data)],
            ['onSortData', () => setSortData(sortFunction(data))],
            ['onRefresh', () => {
                setFocusedRowKey(null)
                if (data) {
                    const { search, sort } = data
                    !sort && setSortData([])
                    !search && setSearchData([])
                    if (search && sort) getData()
                } else getData()
            }],
            ['onDestroy', onDestroy]
        ])
        const func = MapReturn.get(type)
        return func && func()
    }

    DateEvent.useSubscription(CallBackFunc)

    const onFocusedRowChanged = data => {
        DateEvent.emit({ type: 'onFocusedRow', data })
        setFocusedRowKey(data.component.option('focusedRowKey'))
    }

    const onSelectionChanged = (e) => {
        setSelectedRowKeys(e.selectedRowKeys)
        DateEvent.emit({ type: 'onSelected', data: e.selectedRowKeys })
    }




    if (config) {
        if (ORGUUID) {
            return (
                <TreeList
                    id={v4()}
                    keyExpr='uuid'
                    dataStructure="tree"
                    itemsExpr='children'
                    dataSource={Data}
                    allowColumnReordering={true}
                    autoExpandAll={config.autoExpandAll}
                    focusedRowKey={focusedRowKey}
                    focusedRowEnabled={config.focusedRowEnabled}
                    showBorders={config.showBorders}
                    showRowLines={config.showRowLines}
                    showColumnLines={config.showColumnLines}
                    rowAlternationEnabled={config.rowAlternationEnabled}
                    showColumnHeaders={config.showColumnHeaders}
                    allowColumnResizing={config.allowColumnResizing}
                    columnResizingMode={config.columnResizingMode}
                    onExporting={onExporting}
                    defaultSelectedRowKeys={SelectedRowKeys}
                    onSelectionChanged={onSelectionChanged}
                    onFocusedRowChanged={onFocusedRowChanged}
                >

                    <DevFieldTemplate fieldArr={fieldArr} fieldRender={fieldRender} />
                    <DevRowOptionTemplate data={rowStyle} />

                    {/* 固定列 */}
                    <ColumnFixing enabled={config.columnFixingEnabled} />
                    {/* 列选择器 */}
                    <ColumnChooser
                        enabled={config.columnChooserEnabled}
                        title={config.columnChooserTitle}
                        mode={config.columnChooserMode}
                        width={config.columnChooserWidth}
                        height={config.columnChooserHeight}
                    >
                        <Position my="right top" at="right bottom" of=".dx-treelist-column-chooser-button" />
                        <ColumnChooserSearch
                            enabled={config.columnChooserSearch}
                            timeout={config.columnChooserTimeout}
                            editorOptions={{ placeholder: config.columnChooserPlaceholder }}
                        />
                        <ColumnChooserSelection
                            allowSelectAll={config.ColumnChooserAllowSelectAll}
                            selectByClick={config.ColumnChooserSelectByClick}
                            recursive={config.ColumnChooserRecursive}
                        />
                    </ColumnChooser>
                    {/* 排序 */}
                    <Sorting
                        mode={config.Sortingmode}
                        showSortIndexes={config.SortingshowSortIndexes}
                        ascendingText={config.SortingascendingText}
                        descendingText={config.SortingdescendingText}
                        clearText={config.SortingclearText}
                    />
                    {/* 选择 */}
                    <Selection
                        mode={config.SelectionMode}
                        allowSelectAll={config.SelectionAllowSelectAll}
                        selectAllMode={config.SelectionSelectAllMode}
                        showCheckBoxesMode={config.SelectionShowCheckBoxesMode}
                    />
                    {/* 过滤器 */}
                    <HeaderFilter
                        visible={config.HeaderFilterVisible}
                        allowSelectAll={config.HeaderFilterAllowSelectAll}
                        width={config.HeaderFilterWidth}
                        height={config.HeaderFilterHeight}
                    >
                        <Search enabled={config.HeaderFilterEnabled} />
                    </HeaderFilter>
                    {/* 头部搜索 */}
                    <SearchPanel
                        visible={config.SearchPanelVisible}
                        highlightCaseSensitive={config.SearchPanelHighlightCaseSensitive}
                        highlightSearchText={config.SearchPanelHighlightSearchText}
                        placeholder={config.SearchPanelPlaceholder}
                        searchVisibleColumnsOnly={config.SearchPanelSearchVisibleColumnsOnly}
                        defaultText={config.SearchPanelText}
                        width={config.SearchPanelWidth}
                    />
                    {/* 行内搜索 */}
                    <FilterRow
                        visible={config.FilterRowVisible}
                        applyFilter={config.FilterRowApplyFilter}
                        applyFilterText={config.FilterRowApplyFilterText}
                    />
                    <Scrolling
                        rowRenderingMode="virtual"
                        columnRenderingMode="virtual"
                        mode="virtual"
                        scrollByContent={true}
                        showScrollbar='onHover'
                    />
                    <Paging defaultPageSize={1000000} />
                </TreeList>
            )
        }
        else {
            return <Skeleton active paragraph={{ rows: 24 }} />
        }
    } else {
        return (
            <Result
                status="404"
                title="未检测到模板信息"
                subTitle="抱歉,未检测到模板配置信息,请检查网络或联系管理员!"
            />
        )
    }
}

// OLAP
const DevExtremeOLAPGrid = ({ menuUuid, config, APIdata, fieldRender, DateEvent, rowStyle }) => {
    const { method, apiUrl, fieldArr, params, fieldMenu } = APIdata
    const filedShow = fieldRender.filter(v => v.visible)

    const pivotRef = useRef()
    const [Data, setData] = useState()
    const [ORGUUID, setORGUUID] = useState()
    const [SearchData, setSearchData] = useState({})
    const { updateDevPivot } = devChartsStore()
    const { send } = useRequest(data => Http(data), { immediate: false })

    const getData = () => {
        send({ method: method, url: apiUrl, params: { ...strOfurlParamsFunc(params), menuUuid, organizationUuid: ORGUUID, ...SearchData } }).then(async res => {
            const fieldsArr = fieldArr
                .filter(item => filedShow.some(obj => obj.id === item.id))
                .map(item => ({
                    dataField: item.dataField,
                    caption: item.caption,
                    summaryType: 'sum', format: item.format ? { type: item.formatType, precision: item.formatPrecision } : false
                }))
            const olapMapping = { fields: fieldsArr, store: res.data.list }
            setData(new PivotGridDataSource(olapMapping))
        })
    }

    useEffect(() => {
        if (ORGUUID && fieldRender.length !== 0) { getData() }
    }, [ORGUUID, SearchData, fieldRender])

    const CallBackFunc = (e) => {
        const { type, data } = e
        const MapReturn = new Map([
            ['onSelectOrg', () => setORGUUID(data)],
            ['onSearchData', () => setSearchData(data)],
            ['onRefresh', () => getData()]
        ])
        const func = MapReturn.get(type)
        return func && func()
    }

    DateEvent.useSubscription(CallBackFunc)

    const onExportingOLAP = e => {
        const workbook = new Workbook()
        const worksheet = workbook.addWorksheet('Sales')
        exportPivotGrid({ component: e.component, worksheet }).then(() => {
            workbook.xlsx.writeBuffer().then((buffer) => saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'OLAP.xlsx'))
        })
    }

    // 统计方式
    const setSummaryType = (args, sourceField) => {
        Data.field(sourceField.index, { summaryType: args.itemData.value })
        Data.load();
    }

    const setPrecisionType = (type, args, sourceField) => {
        Data.field(sourceField.index, { format: { type, precision: args.itemData.value } })
        Data.load();
    }

    const onContextMenuPreparing = e => {
        const sourceField = e.field
        if (sourceField) {
            const menuItems = []
            const numebrItems = [
                {
                    text: '小数',
                    value: 'fixedPoint',
                    items: () => [...Array(10)].map((_, index) => ({
                        text: `保留 ${index} 位小数`, value: index, onItemClick(e) { setPrecisionType('fixedPoint', e, sourceField) }
                    }))
                },
                {
                    text: '比例',
                    value: 'percent',
                    items: () => [...Array(10)].map((_, index) => ({
                        text: `保留 ${index} 位小数`, value: index, onItemClick(e) { setPrecisionType('percent', e, sourceField) }
                    }))
                },
                {
                    text: '货币',
                    value: 'currency',
                    items: () => [...Array(10)].map((_, index) => ({
                        text: `保留 ${index} 位小数`, value: index, onItemClick(e) { setPrecisionType('currency', e, sourceField) }
                    }))
                },
            ]

            e.items.push({ text: '统计方式', items: menuItems })
            e.items.push({ text: '数值类型', items: numebrItems })

            MappingData.System__summaryType.forEach(item => {
                menuItems.push({
                    text: item.label,
                    value: item.value,
                    onItemClick(e) { setSummaryType(e, sourceField) }
                })
            })
        }
    }

    useEffect(() => { updateDevPivot(pivotRef) }, [pivotRef])

    const loadState = useCallback(async () => {
        const layout = localStorage.getItem(fieldMenu)
        if (!layout) {
            try {
                const layApi = await Http({ method: 'get', url: 'dictionary/GetJsonInfoByUuid', params: { uuid: `OLAPLayout/${fieldMenu}` } })
                localStorage.setItem(fieldMenu, JSON.stringify(layApi))
                return layApi
            } catch (err) {
                console.log('无布局信息')
            }
        } else {
            return JSON.parse(layout)
        }
    }, [])

    const saveState = useCallback((data) => {
        const layout = localStorage.getItem(fieldMenu)
        if (JSON.stringify(data) !== layout) localStorage.setItem(fieldMenu, JSON.stringify(data))
    }, [])

    if (Data)
        return (
            <PivotGrid
                id={v4()}
                ref={pivotRef}
                dataSource={Data}
                allowSorting={config.allowSorting}
                allowSortingBySummary={config.allowSortingBySummary}
                allowFiltering={config.allowFiltering}
                allowExpandAll={config.allowExpandAll}
                showBorders={config.showBorders}
                rowHeaderLayout={config.rowHeaderLayout}
                showTotalsPrior={config.showTotalsPrior}
                dataFieldArea={config.dataFieldArea}
                showColumnTotals={config.showColumnTotals}
                showColumnGrandTotals={config.showColumnGrandTotals}
                showRowTotals={config.showRowTotals}
                showRowGrandTotals={config.showRowGrandTotals}
                onExporting={onExportingOLAP}
                onContextMenuPreparing={onContextMenuPreparing}
            >
                <FieldChooser
                    enabled={config.fieldChooserEnabled}
                    title={config.fieldChooserTitle}
                    layout={config.fieldChooserLayout}
                    width='60vh'
                    height='80vh'
                    allowSearch={config.fieldChooserAllowSearch}
                    applyChangesMode={config.fieldChooserApplyChangesMode}
                />
                <FieldPanel
                    visible={config.fieldPanelVisible}
                    allowFieldDragging={config.fieldPanelAllowFieldDragging}
                    showColumnFields={config.fieldPanelShowColumnFields}
                    showRowFields={config.fieldPanelShowRowFields}
                    showDataFields={config.fieldPanelShowDataFields}
                    showFilterFields={config.fieldPanelShowFilterFields}
                />
                <Export enabled={config.export} />
                <StateStoring
                    enabled={true}
                    type="custom"
                    customLoad={loadState}
                    customSave={saveState}
                    savingTimeout={500}
                />
                <Scrolling
                    rowRenderingMode="virtual"
                    columnRenderingMode="virtual"
                    mode="virtual"
                    scrollByContent={true}
                    showScrollbar='onHover'
                />
            </PivotGrid>
        )
}
// 机构树
const DevOrgTreeTemplate = ({ style, uuid, APIdata, DateEvent }) => {
    const { updateModel } = modelStore()
    const { orgMethod, orgUrl, isSearch } = APIdata
    const STYLE = style || AdminRouter.FlowMenuTreStyle
    const { isFold, status } = STYLE
    const [ALL, setAll] = useState([])
    const [STATUS, setSTATUS] = useState(status)
    const [SELECT, setSELECT] = useState([])
    const [OPENKEY, setOPENKEY] = useState([])
    const [TreeData, setTreeData] = useState([])

    const [SEARCH, setSEARCH] = useState({})


    const treeStyle = {
        '--iconSize': STYLE.iconSize,
        '--iconColor': STYLE.iconColor,
        '--iconShadowX': STYLE.iconShadowX,
        '--iconShadowY': STYLE.iconShadowY,
        '--iconShadowS': STYLE.iconShadowS,
        '--iconShadowB': STYLE.iconShadowB,
        '--fontColor': STYLE.fontColor,
        '--fontFamily': STYLE.fontFamily,
        '--fontWeight': STYLE.fontWeight,
        '--fontStyle': STYLE.fontStyle,
        '--fontSize': STYLE.fontSize,
        '--fontShadowX': STYLE.fontShadowX,
        '--fontShadowY': STYLE.fontShadowY,
        '--fontShadowS': STYLE.fontShadowS,
        '--fontShadowB': STYLE.fontShadowB,
        '--activeBack': STYLE.activeBack,
        '--activeColor': STYLE.activeColor,
        '--activeShadowB': STYLE.activeShadowB,
    }

    const onStatus = () => {
        setSTATUS(e => {
            if (e) setOPENKEY([])
            else setOPENKEY(ALL)
            return !e
        })
    }

    const onSelect = (e) => {
        if (e.length === 0) return
        setSELECT(e)
        DateEvent.emit({ type: 'onSelectOrg', data: e[0] })
    }

    const { send } = useRequest(data => Http(data), { immediate: false })

    const getOrgData = (data = {}) => {
        send({ method: orgMethod, url: orgUrl, params: { MenuType: uuid, ...data } }).then(res => {
            const { list, all, defaultvalue } = res.data
            setTreeData(list)
            setAll(all)
            setSELECT([defaultvalue])
            setOPENKEY(status ? all : [])
            setSEARCH(data)
            DateEvent.emit({ type: 'onSelectOrg', data: defaultvalue })
        })
    }

    useMount(() => {
        getOrgData()
        setSEARCH({})
    })

    const onSearchEvent = useEventEmitter()
    onSearchEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'onFormBack') {
            getOrgData(data)
            onSearchEvent.emit({ type: 'onClearBox' })
        }
    })

    const onClear = () => getOrgData()

    const onSearch = () => {
        updateModel({ title: "组织机构搜索", type: 'SearchForm', width: 480, data: { fields: APIdata.searchArr, Event: onSearchEvent, init: SEARCH } })
    }



    return (
        <div className='TreeTemplate' style={treeStyle}>
            {isSearch &&
                <div className='SearchBox'>
                    <Button style={{ flex: 2 }} type='primary' block onClick={onSearch} icon={<SearchOutlined />} >搜索</Button>
                    <Button style={{ flex: 1 }} block ghost danger onClick={onClear} icon={<RedoOutlined />} >重置</Button>
                </div>
            }
            <Tree
                className='TreeBox'
                blockNode
                treeData={TreeData}
                selectedKeys={SELECT}
                expandedKeys={OPENKEY}
                onExpand={setOPENKEY}
                onSelect={onSelect}
                fieldNames={{ key: 'value', title: 'label' }}
            />
            {isFold &&
                <Button
                    type='primary'
                    block
                    onClick={onStatus}
                    icon={STATUS ? <VerticalAlignTopOutlined /> : <VerticalAlignBottomOutlined />}
                >
                    {STATUS ? '收起' : '展开'}
                </Button>
            }
        </div>
    )
}
// 左侧菜单
const DevLeftTemplate = ({ style, OPTdata, DateEvent }) => {
    const { updateModel } = modelStore()
    const { method, url, params, isSearch, searchArr } = OPTdata.treOptions
    const STYLE = style || AdminRouter.FlowMenuTreStyle
    const { isFold, isSelect, status } = STYLE
    const [ALL, setAll] = useState([])
    const [STATUS, setSTATUS] = useState(status)
    const [SELECT, setSELECT] = useState([])
    const [OPENKEY, setOPENKEY] = useState([])
    const [TreeData, setTreeData] = useState([])

    const [SEARCH, setSEARCH] = useState({})

    const treeStyle = {
        '--iconSize': STYLE.iconSize,
        '--iconColor': STYLE.iconColor,
        '--iconShadowX': STYLE.iconShadowX,
        '--iconShadowY': STYLE.iconShadowY,
        '--iconShadowS': STYLE.iconShadowS,
        '--iconShadowB': STYLE.iconShadowB,
        '--fontColor': STYLE.fontColor,
        '--fontFamily': STYLE.fontFamily,
        '--fontWeight': STYLE.fontWeight,
        '--fontStyle': STYLE.fontStyle,
        '--fontSize': STYLE.fontSize,
        '--fontShadowX': STYLE.fontShadowX,
        '--fontShadowY': STYLE.fontShadowY,
        '--fontShadowS': STYLE.fontShadowS,
        '--fontShadowB': STYLE.fontShadowB,
        '--activeBack': STYLE.activeBack,
        '--activeColor': STYLE.activeColor,
        '--activeShadowB': STYLE.activeShadowB,
    }

    const onStatus = () => {
        setSTATUS(e => {
            if (e) setOPENKEY([])
            else setOPENKEY(ALL)
            return !e
        })
    }

    const onSelect = (e) => {
        if (e.length === 0) return
        setSELECT(e)
        DateEvent.emit({ type: 'onLeftTree', data: e[0] })
    }


    const { send } = useRequest(data => Http(data), { immediate: false })

    const onClear = () => getOrgData()

    const onSearch = () => {
        // updateModel({ title: "组织机构搜索", type: 'SearchForm', width: 480, data: { fields: APIdata.searchArr, Event: onSearchEvent, init: SEARCH } })
    }

    useMount(() => {
        send({ method, url, params: { ...strOfurlParamsFunc(params) } }).then(res => {
            setSELECT([res.data.list[0].uuid])
            setTreeData(res.data.list)
            DateEvent.emit({ type: 'onLeftTree', data: res.data.list[0].uuid })
        })
    })



    return (
        <div className='TreeTemplate' style={treeStyle}>
            {isSearch &&
                <div className='SearchBox'>
                    <Button type='primary' block ghost onClick={onSearch} icon={<SearchOutlined />} >搜索</Button>
                    <Button block ghost onClick={onClear} icon={<RedoOutlined />} >重置</Button>
                </div>
            }
            <Tree
                className='TreeBox'
                blockNode
                treeData={TreeData}
                selectedKeys={SELECT}
                expandedKeys={OPENKEY}
                onExpand={setOPENKEY}
                onSelect={onSelect}
                fieldNames={{ key: 'uuid', title: 'tableName' }}
            />
            {isFold &&
                <Button
                    type='primary'
                    block
                    onClick={onStatus}
                    icon={STATUS ? <VerticalAlignTopOutlined /> : <VerticalAlignBottomOutlined />}
                >
                    {STATUS ? '收起' : '展开'}
                </Button>
            }
        </div>
    )
}

const ModelPopSizeMapping = {
    A01: '80vw', A02: '80vw', A03: 1200, A04: 640, A05: '', A06: '90vw', A07: '', A08: '', A09: '',
    B01: '80vw', B02: 800, B03: '', B04: '90vw', B05: '', B06: 640, B07: '80vw', B08: '', B09: '60vw', B15: '640px',
}

// 头部菜单
const DevTopTemplate = ({ uuid, style, DevEvent, DateEvent, TopOptions, APIdata, treeList }) => {
    const { notification, message } = App.useApp()
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()

    const { fieldMenu } = APIdata
    const { send } = useRequest(data => Http(data), { immediate: false })

    const STYLE = style || AdminRouter.FlowMenuTopStyle
    const configStyle = {
        background: ColorCallBack(STYLE.topBack),
        backdropFilter: `blur(${STYLE.topPx}px)`,
        boxShadow: `var(${STYLE.topShadow})`,
        padding: STYLE.topPadding,
        marginBottom: STYLE.topMargin
    }

    const buttonArr = [
        TopOptions.filter(v => v.position === 'left'),
        TopOptions.filter(v => v.position === 'right')
    ]

    const flexStyle = {
        margin: `0 ${STYLE.itemMargin}px`,
        flexDirection: STYLE.itemOrder === 'texticon' ? 'row-reverse' : 'row'
    }

    const iconStyle = {
        fontSize: STYLE.iconSize,
        filter: `drop-shadow(${STYLE.iconShadowX}px ${STYLE.iconShadowY}px ${STYLE.iconShadowS}px ${STYLE.iconShadowB})`
    }

    const textStyle = {
        fontFamily: STYLE.fontFamily,
        fontWeight: STYLE.fontWeight,
        fontStyle: STYLE.fontStyle,
        fontSize: STYLE.fontSize,
        filter: `drop-shadow(${STYLE.fontShadowX}px ${STYLE.fontShadowY}px ${STYLE.fontShadowS}px ${STYLE.fontShadowB})`
    }

    const [SearchData, setSearchData] = useState({})
    const [SortData, setSortData] = useState([])

    const [ORGUUID, setORGUUID] = useState()
    const [TREEUUID, setTREEUUID] = useState()

    const [SelectData, setSelectData] = useState([])


    const CallBackFunc = (e) => {
        const { type, data } = e
        const MapReturn = new Map([
            ['onSearch', () => {
                setSearchData(data)
                DateEvent.emit({ type: 'onSearchData', data })
            }], ['onSort', () => {
                setSortData(data)
                DateEvent.emit({ type: 'onSortData', data })
            }],
            ['onSelectOrg', () => { if (data) getPower(data) }],
        ])
        const func = MapReturn.get(type)
        return func && func()
    }

    DevEvent.useSubscription(CallBackFunc)

    DateEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'onSelectOrg') setORGUUID(data)
        if (type === 'onLeftTree') setTREEUUID(data)
        if (type === 'onSelected') setSelectData(data)
    })

    const onOptionsClick = (e) => {
        const selectData = typeof (e) === 'string' ? TopOptions.find(v => v.uuid === e) : e
        const { type, field, title } = selectData
        switch (type) {
            case 'A01':
                console.log('查看数据', field)
                break;
            case 'A02':
                updateModel({
                    title: title,
                    type: 'OptionsModel',
                    width: ModelPopSizeMapping[type],
                    data: {
                        menuUuid: uuid,
                        config: selectData,
                        fieldArr: APIdata.fieldArr,
                        DevEvent,
                        DateEvent,
                        ORGUUID,
                        addParams: treeList && treeList.isAdd ? `${treeList.addParams}=${TREEUUID}` : null
                    }
                })
                break;
            case 'A03':
                updateModel({
                    title: title,
                    type: 'OptionsModel',
                    width: ModelPopSizeMapping[type],
                    data: { config: selectData, fieldArr: APIdata.fieldArr, DevEvent, init: SearchData }
                })
                break;
            case 'A04':
                updateModel({
                    title: title,
                    type: 'OptionsModel',
                    width: ModelPopSizeMapping[type],
                    data: { config: selectData, fieldArr: APIdata.fieldArr, DevEvent, init: SortData }
                })
                break;
            case 'A05':
                const { search, sort } = selectData
                !sort && setSortData([])
                !search && setSearchData([])
                DateEvent.emit({ type: 'onRefresh', data: { search, sort } })
                break;
            case 'A06':
                updateModel({
                    title: title,
                    type: 'OptionsModel',
                    width: ModelPopSizeMapping[type],
                    data: { config: selectData, DevEvent, ORGUUID, search: { ...SearchData, ...sortFunction(SortData) } }
                })
                break;
            case 'A07':
                if (SelectData.length === 0) {
                    message.info('请先勾选数据!')
                    return false
                }
                updateModel({
                    title: title,
                    type: 'OptionsModel',
                    width: ModelPopSizeMapping[type],
                    data: { config: selectData, DevEvent, DateEvent, init: SelectData }
                })
                break;
            case 'A08':
                const { A08Type, A08Width } = selectData
                if (A08Type === 'A01' || A08Type === 'A05') {
                    updateDrawer({ type: 'OptionsOpen', title, width: A08Width, data: { type: A08Type, DevEvent } })
                }
                if (A08Type === 'A02') {
                    send({
                        method: 'post',
                        url: 'dictionary/SaveJsonInfoByUuid',
                        params: { uuid: `OLAPLayout/${fieldMenu}`, content: window.localStorage.getItem(fieldMenu) }
                    }).then(() => notification.success({ message: '保存成功!', description: '新OLAP布局保存成功!' }))
                }
                if (A08Type === 'A03') {
                    send({ method: 'get', url: 'dictionary/GetJsonInfoByUuid', params: { uuid: `OLAPLayout/${fieldMenu}` } }).then(res => {
                        localStorage.setItem(fieldMenu, JSON.stringify(res))
                        notification.success({ message: '重置成功!', description: '当前布局信息已同步线上!' })
                        DateEvent.emit({ type: 'onRefresh' })
                    })
                }
                if (A08Type === 'A04') {
                    updateModel({
                        title: title,
                        type: 'OptionsOpen',
                        width: A08Width,
                        data: { type: A08Type, DevEvent }
                    })
                }
                if (A08Type === 'B05') {
                    updateModel({
                        title,
                        type: 'WeChatBaseConfig',
                        width: 1500,
                        data: { type: A08Type, DevEvent }
                    })
                }
                break;
            case 'A09':
                const modelMapping = { model: updateModel, drawer: updateDrawer }
                modelMapping[selectData.modelType]({
                    title,
                    type: selectData.openPage,
                    width: selectData.modelWidth,
                    data: { type: selectData.openType, DevEvent, DateEvent, init: SelectData }
                })
                break;
            default:
                break;
        }
    }


    return (
        <div className='TopMenu' style={configStyle}>
            {buttonArr.map((arr, index) =>
                <div key={index}>
                    {arr.map(({ uuid, icon, title, color, type, children }) => {
                        if (type === 'A00') {
                            const items = children.map(item => {
                                return ({
                                    key: item.uuid,
                                    label: (
                                        <Button
                                            type='link'
                                            icon={STYLE.itemOrder.includes('icon') && <div style={iconStyle}>{ICONMapping[item.icon]}</div>}
                                            style={{ color }}
                                            onClick={() => onOptionsClick(item)}
                                        >
                                            <div style={textStyle}>{item.title}</div>
                                        </Button>
                                    )
                                })
                            })
                            return (
                                <Dropdown
                                    key={uuid}
                                    menu={{ items: items }}
                                    trigger={['click']}
                                >
                                    <div style={{ ...flexStyle, color }} >
                                        {STYLE.itemOrder.includes('icon') && <div style={iconStyle}>{ICONMapping[icon]}</div>}
                                        {STYLE.itemOrder.includes('text') && <div style={textStyle}>{title}</div>}
                                    </div>
                                </Dropdown>

                            )
                        } else {
                            return (
                                <div key={uuid} style={{ ...flexStyle, color }} onClick={() => onOptionsClick(uuid)}>
                                    {STYLE.itemOrder.includes('icon') && <div style={iconStyle}>{ICONMapping[icon]}</div>}
                                    {STYLE.itemOrder.includes('text') && <div style={textStyle}>{title}</div>}
                                </div>
                            )
                        }
                    })}
                </div>
            )}
        </div>
    )
}

const DevExtremeMapping = {
    DevExtremeDataGrid,
    DevExtremeTreeGrid,
    DevExtremeOLAPGrid
}

const DevExtremeConfig = ({ uuid, url, MenuType, APIdata, TEMdata, OPTdata, DevEvent }) => {
    const { notification, message } = App.useApp()
    // console.log(uuid, MenuType)
    const { updateModel } = modelStore()
    const { updateDrawer } = drawerStore()
    const { pageList, updateActive, updateList } = pageStore()
    const [ORGUUID, setORGUUID] = useState()
    const [TREEUUID, setTREEUUID] = useState()

    const [FieldRender, setFieldRender] = useState([]) // 字段渲染
    const [FieldSort, setFieldSort] = useState() // 排序渲染
    const [TopOptions, setTopOptions] = useState([])
    const [RowOptions, setRowOptions] = useState([])
    const [FocusedRow, setFocusedRow] = useState()

    const [RenderData, setRenderData] = useState(false) // 渲染数据

    const [UUID, setUUID] = useState()


    useMount(async () => {
        const { userUuid } = await GetIndexedDB('user')
        setUUID(userUuid)
    })


    if (JSON.stringify(APIdata) !== '{}' && JSON.stringify(TEMdata) !== '{}' && JSON.stringify(OPTdata) !== '{}') {
        const { orgTree, leftTemplate, topTemplate, popTemplate, rowTemplate, devTemplate, devConfig, topStyle, treStyle, rowStyle, popStyle, sort } = TEMdata
        const Template = DevExtremeMapping[devTemplate]
        const { send } = useRequest(data => Http(data), { immediate: false })

        const getPower = (organizationUuid) => {
            setORGUUID(organizationUuid)
            send({ method: 'get', url: 'menu/GetMenuByButton', params: { uuid: MenuType, organizationUuid } }).then(power => {
                if (power.length === 0) {
                    notification.error({ key: 'devPage', message: '权限不足!', description: '您未获取到当前页面权限,如有需要请及时联系管理员!', showProgress: true })
                    return false
                }
                setRenderData(true)
                const topArr = filterTreeData(OPTdata.topOptions, power)
                const rowArr = filterTreeData(OPTdata.rowOptions, power)
                const [render] = topArr.filter(v => v.type === 'A01')
                if (!render) {
                    notification.error({ key: 'devPage', message: '权限不足!', description: '您未获取到当前页面查看权限!', showProgress: true })
                    return false
                }
                setTopOptions(topArr)
                setRowOptions(rowArr)
                const { field, bands } = render
                const fieldRender = devTemplate === "DevExtremeDataGrid" ? bands ? bands : field : field
                setFieldRender(fieldRender || [])
                setFieldSort(sort ? sort.field : [])
            })
        }

        const CallBackFunc = (e) => {
            // console.log('CallBackFunc', e)
            const { type, data } = e
            const MapReturn = new Map([
                ['onFocusedRow', () => setFocusedRow(data)],
                ['onLeftTree', () => setTREEUUID(data)],
                ['onSelectOrg', () => { if (data) getPower(data) }]
            ])
            const func = MapReturn.get(type)
            return func && func()
        }

        const DateEvent = useEventEmitter()
        DateEvent.useSubscription(CallBackFunc)

        const items = () => {
            const status = popStyle?.itemOrder || 'icontext'
            const TitleStyle = popStyle ? {
                '--iconSize': popStyle.iconSize + 'px',
                '--iconFilter': `drop-shadow(${popStyle.iconShadowX}px ${popStyle.iconShadowY}px ${popStyle.iconShadowS}px ${popStyle.iconShadowB})`,
                '--fontFamily': popStyle.fontFamily,
                '--fontWeight': popStyle.fontWeight,
                '--fontStyle': popStyle.fontStyle,
                '--fontSize': popStyle.fontSize + 'px',
                '--fontFilter': `drop-shadow(${popStyle.fontShadowX}px ${popStyle.fontShadowY}px ${popStyle.fontShadowS}px ${popStyle.fontShadowB})`,
            } : {}
            const generateOption = (item) => {
                const { uuid, type, title, icon, color, children } = item
                return {
                    key: uuid,
                    label: (
                        <Button
                            type='link'
                            icon={status.includes('icon') && ICONMapping[icon]}
                            style={{ ...TitleStyle, color }}
                            onClick={() => {
                                const updataMapping = ['B08', 'B09', "B15"]
                                if (type === 'B00') return false
                                if (type === 'B11') {
                                    const { isModel } = item
                                    if (isModel) {
                                        updateModel({
                                            title,
                                            type: 'CommonModel',
                                            width: item.modelWidth,
                                            data: { type: 'execute', row: FocusedRow, DateEvent, params: item }
                                        })
                                    } else {
                                        const { modelTips, formMethod, formUrl, formParams, sendData, isData, dataKey, dataMap } = item
                                        const params = sendData.reduce((acc, { key, value }) => {
                                            acc[key] = value;
                                            return acc;
                                        }, {});
                                        if (isData) params[dataMap] = FocusedRow.row.data[dataKey]
                                        send({ method: formMethod, url: formUrl, params: { ...strOfurlParamsFunc(formParams), ...params } }).then(res => {
                                            DateEvent.emit({ type: 'onRefresh' })
                                        })
                                    }
                                    return false
                                }
                                if (type === 'B06') {
                                    const { modelType, modelWidth, openPage, openType } = item
                                    const modelMapping = { model: updateModel, drawer: updateDrawer }
                                    modelMapping[modelType]({
                                        title,
                                        type: openPage,
                                        width: modelWidth || ModelPopSizeMapping[type],
                                        data: {
                                            type: openType,
                                            row: FocusedRow,
                                            DevEvent,
                                            DateEvent,
                                        }
                                    })
                                    return false
                                }
                                if (type === 'B12') {
                                    const { url, pageType, fieldTitle, pageTitle, pageIcon, isData, dataKey } = item
                                    const { uuid } = FocusedRow.row.data
                                    const label = FocusedRow.row.data[fieldTitle] + pageTitle
                                    if (pageList.findIndex(v => v.key === uuid) === -1) {
                                        updateList([...pageList, {
                                            key: isData ? FocusedRow.row.data[dataKey] : uuid, label, url, type: pageType, icon: pageIcon || ''
                                        }])
                                    }
                                    updateActive(uuid)
                                    return false
                                }
                                if (updataMapping.includes(type)) {
                                    updateDrawer({
                                        title,
                                        type: 'OptionsModel',
                                        width: ModelPopSizeMapping[type],
                                        data: { row: FocusedRow, config: item, fieldArr: APIdata.fieldArr, DevEvent, DateEvent, ORGUUID, children }
                                    })
                                } else {
                                    updateModel({
                                        title,
                                        type: 'OptionsModel',
                                        width: ModelPopSizeMapping[type],
                                        data: {
                                            row: FocusedRow,
                                            config: item,
                                            fieldArr: APIdata.fieldArr,
                                            DevEvent,
                                            DateEvent,
                                            ORGUUID,
                                            addParams: leftTemplate && OPTdata.treOptions.isAdd ?
                                                `${OPTdata.treOptions.addParams}=${TREEUUID}` : null
                                        }
                                    })
                                }
                            }}
                        >
                            {status.includes('text') && title}
                        </Button>
                    )
                }
            }
            const generateChildren = (children) => (children.map(item => generateOption(item)))
            const optimizeData = () => {
                if (!Array.isArray(RowOptions)) { return [] }
                return RowOptions.map(item => {
                    const { type, children, judge, jugdeField, jugdeValue } = item
                    if (judge && !jugdeValue.split(',').includes(FocusedRow.row.data[jugdeField].toString())) return false
                    return ({ ...generateOption(item), ...(type === 'B00' ? { children: generateChildren(children) } : {}) })
                })
            }
            return FocusedRow ? optimizeData(RowOptions) : []
        }

        useMount(async () => {
            if (!!!orgTree) {
                const { orgMethod, orgUrl, orgParams } = APIdata
                send({ method: orgMethod, url: orgUrl, params: { ...orgParams, MenuType } }).then(res => {
                    DateEvent.emit({ type: 'onSelectOrg', data: res.data.defaultvalue })
                })
            }
        })


        useEffect(() => {
            return () => DateEvent.emit({ type: 'onDestroy' })
        }, [])


        useEffect(() => {
            // 定期检查内存使用情况
            const interval = setInterval(() => {
                if (typeof window.performance !== 'undefined') {
                    const memory = window.performance.memory;
                    if (memory && memory.usedJSHeapSize > memory.jsHeapSizeLimit * 0.8) {
                        console.warn('内存使用过高，可能存在内存泄漏');
                        // 可以在这里执行一些清理操作
                    }
                }
            }, 3000); // 每30秒检查一次

            return () => clearInterval(interval);
        }, []);


        return (
            <div className='DevExtremeConfig'>
                <Splitter>
                    {orgTree &&
                        <Item size={treStyle?.size || 240} resizable={treStyle?.resizable} collapsible={treStyle?.collapsible}>
                            <DevOrgTreeTemplate style={treStyle} uuid={uuid} APIdata={APIdata} DateEvent={DateEvent} />
                        </Item>
                    }
                    <Item
                        render={() => (
                            <div className='DevPage'>
                                {/* 全局操作 */}
                                {topTemplate &&
                                    <DevTopTemplate
                                        uuid={uuid}
                                        style={topStyle}
                                        DevEvent={DevEvent}
                                        DateEvent={DateEvent}
                                        TopOptions={TopOptions}
                                        FieldSort={FieldSort}
                                        APIdata={APIdata}
                                        treeList={leftTemplate && OPTdata.treOptions}
                                    />
                                }
                                <Splitter>
                                    {leftTemplate &&
                                        <Item size='240px' resizable={true} collapsible={true}>
                                            <DevLeftTemplate style={treStyle} DateEvent={DateEvent} OPTdata={OPTdata} />
                                        </Item>
                                    }
                                    <Item render={() => (
                                        <div className='DevGrid'>
                                            <Dropdown
                                                menu={{ items: items() }}
                                                trigger={['contextMenu']}
                                            >
                                                <div className='DevTemplate'>
                                                    <Template
                                                        menuUuid={uuid}
                                                        DateEvent={DateEvent}
                                                        orgTree={orgTree}
                                                        APIdata={APIdata}   // 接口配置
                                                        config={devConfig}  // 组件配置
                                                        rowStyle={rowStyle} // 行内样式
                                                        FieldSort={FieldSort} // 默认排序
                                                        fieldRender={FieldRender}
                                                        treeList={leftTemplate && OPTdata.treOptions}
                                                    />
                                                </div>
                                            </Dropdown>
                                        </div>
                                    )} />
                                </Splitter>
                            </div>
                        )}
                    />
                </Splitter>
                {(port || UUID === '1e99e116-6ec0-425c-87b4-64dd2ce458e2') &&
                    <FloatButton type='primary' onClick={() => DevEvent.emit({ type: 'onUpDate' })} />
                }
            </div>
        )
    } else {
        return (
            <Result
                status="404"
                title="当前页面未配置"
                subTitle="抱歉,当前页面未检测到配置文件.请及时联系管理员!"
                extra={(port || UUID === '1e99e116-6ec0-425c-87b4-64dd2ce458e2') &&
                    <Button type="primary" onClick={() => DevEvent.emit({ type: 'onUpDate' })}>路由配置</Button>
                }
            />
        )
    }
};

export default DevExtremeConfig;

